package com.cjh.wechat.websocket.controller;

import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import com.cjh.wechat.commom.pojo.User;

@Resource
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor
{
    private static Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
    
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception
    {
        logger.debug("-------拦截器前----------");
        HttpSession session = ((ServletServerHttpRequest) request).getServletRequest().getSession(false);
        if (session != null)
        {
            User user = (User) session.getAttribute("USERINFO");
            if (user == null)
            {
                return false;
            }
            else
            {
                attributes.put("id", user.getId());
            }
        }
        return true;
    }
    
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex)
    {
        logger.debug("-------拦截器后----------");
        super.afterHandshake(request, response, wsHandler, ex);
    }
    
}
